<template>
  <div class="address-manage">
    <!-- 添加一个隐藏的容器用于地图实例 -->
    <div id="amap-container" style="display: none;"></div>
    <div class="page-header">
      <h2>地址管理</h2>
      <el-button type="primary" @click="showAddressDialog()">新增地址</el-button>
    </div>

    <!-- 地址列表 -->
    <div class="address-list">
      <el-card v-for="(address, index) in addresses" :key="address.id" class="address-item">
        <div class="address-content">
          <div class="address-info">
            <div class="receiver-info">
              <span class="name">{{ address.receiverName }}</span>
              <span class="phone">{{ address.receiverPhone }}</span>
              <el-tag size="mini" type="success" v-if="address.isDefault">默认地址</el-tag>
            </div>
            <div class="address-detail">
              {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}
            </div>
          </div>
          <div class="address-actions">
            <el-button type="text" @click="showAddressDialog(address, index)">编辑</el-button>
            <el-button type="text" @click="setDefault(address)" v-if="!address.isDefault">设为默认</el-button>
            <el-button type="text" class="delete-btn" @click="deleteAddress(address)">删除</el-button>
          </div>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-if="addresses.length === 0" class="empty-state">
        <i class="el-icon-location-outline"></i>
        <p>暂无收货地址，请添加</p>
      </div>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="addressForm" :rules="rules" ref="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="receiverPhone">
          <el-input v-model="addressForm.receiverPhone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <div class="region-wrapper">
            <el-cascader
              v-model="addressForm.region"
              :options="regionOptions"
              :props="{
                value: 'name',
                label: 'name',
                children: 'children',
                checkStrictly: false,
                expandTrigger: 'hover'
              }"
              @change="handleRegionChange"
              placeholder="请选择所在地区">
            </el-cascader>
            <el-button type="text" @click="getLocation" class="location-btn">
              <i class="el-icon-location"></i> 定位当前位置
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input type="textarea" v-model="addressForm.detailAddress" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false" :disabled="submitting">取 消</el-button>
        <el-button 
          type="primary" 
          @click="saveAddress" 
          :loading="submitting"
          :disabled="submitting">
          {{ submitting ? '保存中...' : '确 定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserAddress',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    return {
      addresses: [],
      dialogVisible: false,
      dialogTitle: '新增收货地址',
      editingIndex: -1,
      addressForm: {
        id: null,
        receiverName: '',
        receiverPhone: '',
        region: [],
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      rules: {
        receiverName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
          { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
        ]
      },
      regionOptions: [], // 省市区数据
      locationLoading: false,
      submitting: false, // 添加提交状态标记
    };
  },
  created() {
    this.loadAddresses();
    this.loadRegionData();
  },
  methods: {
    // 加载地址列表
    loadAddresses() {
      this.request.get('/address/list').then(res => {
        if (res.code === 1 || res.code === '200') {
          this.addresses = res.data;
        } else {
          this.$message.error(res.msg || '加载地址失败');
        }
      });
    },

    // 加载省市区数据
    loadRegionData() {
      // 使用腾讯地图行政区划API
      this.request.get('https://apis.map.qq.com/ws/district/v1/list?key=ZHZBZ-NDPKU-DQTVJ-2I4XH-PQKEK-VWBZJ').then(res => {
        if (res && res.status === 0) {
          // 转换数据格式
          this.regionOptions = this.formatRegionData(res.result);
        } else {
          // 如果API调用失败，使用备用数据源
          this.loadBackupRegionData();
        }
      }).catch(() => {
        this.loadBackupRegionData();
      });
    },

    // 格式化地区数据
    formatRegionData(data) {
      const [provinces, cities, districts] = data;
      return provinces.map(province => {
        const provinceObj = {
          name: province.fullname,
          children: []
        };

        // 获取该省的所有城市
        const provinceCities = cities.filter(city => city.parentId === province.id);
        provinceObj.children = provinceCities.map(city => {
          const cityObj = {
            name: city.fullname,
            children: []
          };

          // 获取该市的所有区县
          const cityDistricts = districts.filter(district => district.parentId === city.id);
          cityObj.children = cityDistricts.map(district => ({
            name: district.fullname
          }));

          return cityObj;
        });

        return provinceObj;
      });
    },

    // 备用数据源
    loadBackupRegionData() {
      // 使用高德地图行政区划API
      this.request.get('https://restapi.amap.com/v3/config/district?key=c40c2c9e5d3f8f9c0c2c2c2c2c2c2c2c&subdistrict=3&extensions=base').then(res => {
        if (res && res.status === '1') {
          this.regionOptions = this.formatAmapData(res.districts);
        } else {
          // 如果两个API都失败了，使用静态数据
          this.useStaticData();
        }
      }).catch(() => {
        this.useStaticData();
      });
    },

    // 格式化高德地图数据
    formatAmapData(districts) {
      return districts.map(province => ({
        name: province.name,
        children: province.districts.map(city => ({
          name: city.name,
          children: city.districts.map(district => ({
            name: district.name
          }))
        }))
      }));
    },

    // 使用静态数据
    useStaticData() {
      this.regionOptions = [
        {
          name: '北京市',
          children: [
            {
              name: '北京市',
              children: [
                { name: '东城区' },
                { name: '西城区' },
                { name: '朝阳区' },
                { name: '海淀区' },
                { name: '丰台区' },
                { name: '石景山区' },
                { name: '门头沟区' },
                { name: '房山区' },
                { name: '通州区' },
                { name: '顺义区' },
                { name: '昌平区' },
                { name: '大兴区' },
                { name: '怀柔区' },
                { name: '平谷区' },
                { name: '密云区' },
                { name: '延庆区' }
              ]
            }
          ]
        },
        {
          name: '上海市',
          children: [
            {
              name: '上海市',
              children: [
                { name: '黄浦区' },
                { name: '徐汇区' },
                { name: '长宁区' },
                { name: '静安区' },
                { name: '普陀区' },
                { name: '虹口区' },
                { name: '杨浦区' },
                { name: '闵行区' },
                { name: '宝山区' },
                { name: '嘉定区' },
                { name: '浦东新区' },
                { name: '金山区' },
                { name: '松江区' },
                { name: '青浦区' },
                { name: '奉贤区' },
                { name: '崇明区' }
              ]
            }
          ]
        },
        {
          name: '广东省',
          children: [
            {
              name: '广州市',
              children: [
                { name: '越秀区' },
                { name: '海珠区' },
                { name: '荔湾区' },
                { name: '天河区' },
                { name: '白云区' },
                { name: '黄埔区' },
                { name: '番禺区' },
                { name: '花都区' },
                { name: '南沙区' },
                { name: '从化区' },
                { name: '增城区' }
              ]
            },
            {
              name: '深圳市',
              children: [
                { name: '福田区' },
                { name: '罗湖区' },
                { name: '南山区' },
                { name: '盐田区' },
                { name: '宝安区' },
                { name: '龙岗区' },
                { name: '龙华区' },
                { name: '坪山区' },
                { name: '光明区' }
              ]
            }
            // 可以继续添加其他城市
          ]
        }
        // 可以继续添加其他省份
      ];
    },

    // 获取当前位置
    getLocation() {
      if (this.locationLoading) return;
      this.locationLoading = true;

      // 使用高德地图 API 获取定位
      if (window.AMap) {
        this.getAMapLocation();
      } else {
        // 如果还没有加载高德地图 JS，先加载再定位
        this.loadAMap().then(() => {
          this.getAMapLocation();
        });
      }
    },

    // 加载高德地图 JS
    loadAMap() {
      return new Promise((resolve, reject) => {
        if (window.AMap) {
          resolve(window.AMap);
          return;
        }

        const script = document.createElement('script');
        script.type = 'text/javascript';
        // 使用安全协议，添加必要的插件
        script.src = `https://webapi.amap.com/maps?v=2.0&key=c40c2c9e5d3f8f9c0c2c2c2c2c2c2c2c&plugin=AMap.Geocoder,AMap.Geolocation,AMap.CitySearch`;
        script.onerror = reject;
        script.onload = () => resolve(window.AMap);
        document.head.appendChild(script);
      });
    },

    // 使用高德地图进行定位
    getAMapLocation() {
      if (!window.AMap) {
        this.$message.error('地图加载失败，请刷新页面重试');
        this.locationLoading = false;
        return;
      }

      // 使用浏览器定位
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const lng = position.coords.longitude;
            const lat = position.coords.latitude;
            
            // 使用高德地图逆地理编码服务
            window.AMap.plugin('AMap.Geocoder', () => {
              const geocoder = new window.AMap.Geocoder({
                radius: 1000,
                extensions: 'all'
              });
              
              geocoder.getAddress([lng, lat], (status, result) => {
                this.locationLoading = false;
                
                if (status === 'complete' && result.info === 'OK') {
                  const addressComponent = result.regeocode.addressComponent;
                  const formattedAddress = result.regeocode.formattedAddress;
                  
                  // 更新地址表单
                  this.addressForm.region = [
                    addressComponent.province,
                    addressComponent.city,
                    addressComponent.district
                  ];
                  this.addressForm.province = addressComponent.province;
                  this.addressForm.city = addressComponent.city;
                  this.addressForm.district = addressComponent.district;
                  
                  // 移除省市区信息，只保留详细地址
                  let detailAddress = formattedAddress;
                  if (addressComponent.province) {
                    detailAddress = detailAddress.replace(addressComponent.province, '');
                  }
                  if (addressComponent.city) {
                    detailAddress = detailAddress.replace(addressComponent.city, '');
                  }
                  if (addressComponent.district) {
                    detailAddress = detailAddress.replace(addressComponent.district, '');
                  }
                  this.addressForm.detailAddress = detailAddress.trim();

                  this.$message.success('定位成功');
                  
                  // 触发级联选择器的更新
                  this.$nextTick(() => {
                    this.handleRegionChange(this.addressForm.region);
                  });
                } else {
                  this.$message.error('获取地址信息失败，请手动选择');
                }
              });
            });
          },
          (error) => {
            this.locationLoading = false;
            let errorMessage = '定位失败，请手动选择地址';
            switch (error.code) {
              case error.PERMISSION_DENIED:
                errorMessage = '请允许浏览器获取位置信息';
                break;
              case error.POSITION_UNAVAILABLE:
                errorMessage = '位置信息不可用';
                break;
              case error.TIMEOUT:
                errorMessage = '获取位置信息超时';
                break;
            }
            this.$message.error(errorMessage);
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
          }
        );
      } else {
        this.locationLoading = false;
        this.$message.error('您的浏览器不支持定位功能');
      }
    },

    // 显示地址对话框
    showAddressDialog(address, index) {
      this.dialogVisible = true;
      this.editingIndex = index;
      this.submitting = false; // 重置提交状态
      
      if (address) {
        this.dialogTitle = '编辑收货地址';
        this.addressForm = {
          id: address.id,
          receiverName: address.receiverName,
          receiverPhone: address.receiverPhone,
          region: [address.province, address.city, address.district],
          province: address.province,
          city: address.city,
          district: address.district,
          detailAddress: address.detailAddress,
          isDefault: address.isDefault,
          userId: address.userId // 保存用户ID
        };
      } else {
        this.dialogTitle = '新增收货地址';
        this.addressForm = {
          id: null,
          receiverName: '',
          receiverPhone: '',
          region: [],
          province: '',
          city: '',
          district: '',
          detailAddress: '',
          isDefault: false,
          userId: 1 // 设置默认用户ID
        };
      }
    },

    // 处理地区选择变化
    handleRegionChange(value) {
      if (value.length === 3) {
        this.addressForm.province = value[0];
        this.addressForm.city = value[1];
        this.addressForm.district = value[2];
      }
    },

    // 保存地址
    saveAddress() {
      if (this.submitting) {
        return;
      }

      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          this.submitting = true;
          const url = this.addressForm.id ? '/address/update' : '/address/add';
          
          this.request.post(url, {
            ...this.addressForm,
            userId: 1,
          }).then(res => {
            if (res.code === 1 || res.code === '200') {
              this.$message.success('保存成功');
              this.dialogVisible = false;
              this.loadAddresses();
            } else {
              this.$message.error(res.msg || '保存失败');
            }
          }).catch(error => {
            console.error('保存地址失败:', error);
            this.$message.error('保存失败，请重试');
          }).finally(() => {
            this.submitting = false;
          });
        }
      });
    },

    // 设置默认地址
    setDefault(address) {
      this.request.post('/address/setDefault', { id: address.id }).then(res => {
        if (res.code === 1 || res.code === '200') {
          this.$message.success('设置成功');
          this.loadAddresses();
        } else {
          this.$message.error(res.msg || '设置失败');
        }
      });
    },

    // 删除地址
    deleteAddress(address) {
      this.$confirm('确定要删除这个地址吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.request.post('/address/delete', { id: address.id }).then(res => {
          if (res.code === 1 || res.code === '200') {
            this.$message.success('删除成功');
            this.loadAddresses();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        });
      });
    }
  }
};
</script>

<style scoped>
.address-manage {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background: #f5f5f5;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
  font-weight: 500;
  position: relative;
  padding-left: 12px;
}

.page-header h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: #e1251b;
  border-radius: 2px;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 15px;
}

.address-item {
  border-radius: 4px;
  transition: all 0.3s;
  background: #fff;
  border: 1px solid #e8e8e8;
  position: relative;
  overflow: hidden;
}

.address-item:hover {
  border-color: #e1251b;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
}

.address-item:hover .address-actions {
  opacity: 1;
  transform: translateY(0);
}

.address-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
}

.receiver-info {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-right: 12px;
}

.phone {
  color: #666;
  margin-right: 12px;
  font-family: Arial, sans-serif;
}

.el-tag {
  height: 20px;
  line-height: 18px;
  padding: 0 6px;
  font-size: 12px;
  border-radius: 2px;
  background-color: #fff1f0;
  border-color: #ffccc7;
  color: #e1251b;
}

.address-detail {
  color: #666;
  line-height: 1.6;
  font-size: 14px;
  margin-bottom: 8px;
}

.address-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 12px 16px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
  opacity: 0.9;
  transition: all 0.3s;
}

.address-actions .el-button {
  padding: 0;
  font-size: 13px;
}

.address-actions .el-button:hover {
  color: #e1251b;
}

.delete-btn {
  color: #999 !important;
}

.delete-btn:hover {
  color: #f56c6c !important;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background: #fff;
  border-radius: 4px;
  margin-top: 20px;
}

.empty-state i {
  font-size: 56px;
  color: #e8e8e8;
  margin-bottom: 16px;
}

.empty-state p {
  color: #999;
  font-size: 14px;
  margin: 8px 0 0;
}

.el-dialog {
  max-width: 90%;
}

.el-dialog__header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.region-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.region-wrapper .el-cascader {
  width: 100%;
}

.location-btn {
  color: #1890ff;
  white-space: nowrap;
  padding: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

.location-btn i {
  margin-right: 4px;
  font-size: 16px;
}

.location-btn:hover {
  color: #40a9ff;
}

#amap-container {
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: -1;
  opacity: 0;
}

@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .address-item {
    margin-bottom: 12px;
  }
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: normal;
  color: #333;
}

.el-input__inner,
.el-textarea__inner {
  border-color: #dcdfe6;
}

.el-input__inner:hover,
.el-textarea__inner:hover {
  border-color: #c0c4cc;
}

.el-input__inner:focus,
.el-textarea__inner:focus {
  border-color: #e1251b;
}

.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #e1251b;
  border-color: #e1251b;
}

.el-checkbox__input.is-checked + .el-checkbox__label {
  color: #e1251b;
}

.el-button--primary {
  background-color: #e1251b;
  border-color: #e1251b;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #f1403c;
  border-color: #f1403c;
}

.el-button--primary.is-disabled {
  background-color: #fab6b6;
  border-color: #fab6b6;
}
</style> 